package eu.codlab.game.gameba;

import eu.codlab.androidemu.Emulator.FrameUpdateListener;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class EmulatorViewControl extends View
{//implements SurfaceHolder.Callback {
	public EmulatorViewControl(Context context, AttributeSet attrs) {
		super(context, attrs);

		//final SurfaceHolder holder = getHolder();
		//holder.setFormat(PixelFormat.TRANSPARENT);
		//holder.setFixedSize(Emulator.VIDEO_W, Emulator.VIDEO_H);
		//holder.setKeepScreenOn(true);
		//holder.addCallback(this);

		setFocusableInTouchMode(true);
		requestFocus();

		listener = new VirtualKeypad(context);
		listener.setSurfaceView(this);
		//this.getHolder().addCallback(listener);
		//if(keypadview != null){
		//emulatorView2.getHolder().addCallback(keypad);
		this.setOnTouchListener(listener);
		//emulatorView.setFrameUpdateListener(keypad);
		this.setVirtualKeypad(listener);
	}

	private VirtualKeypad listener;
	public VirtualKeypad getVirtualKeypad(){
		return listener;
	}
	public void setVirtualKeypad(VirtualKeypad l){
		listener = l;
	}

	public int getSpaceHeight(){
		if(listener != null)
			return this.getHeight() - listener.getSpaceHeight();
		return 0;
	}
	public int getSpaceWidth(){
		if(listener != null)
			return this.getWidth() - listener.getSpaceWidth();
		return 0;
	}
	EmulatorView view;
	public void setEmulatorView(EmulatorView view){
		if(this.view == null){
			this.view = view;
			view.setSurroundControllers(this);
		}
	}

	public void onDraw(Canvas canvas){
		if(canvas == null || this.getWidth() <= 0 ||
				this.getHeight() <= 0)
			return;
		listener.resize(this.getWidth(), this.getHeight());
		listener.draw(canvas);
	}
	public void surfaceCreated(SurfaceHolder holder) {
		Canvas canvas = holder.lockCanvas();
		onDraw(canvas);
		holder.unlockCanvasAndPost(canvas);
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		//stopThread();
	}

	public void surfaceChanged(SurfaceHolder holder,
			int format, int width, int height) {
		listener.resize(width, height);
		reDraw();
	}
	public void onSizeChanged(int w, int h, int oldw, int oldh){
		listener.resize(w, h);
		reDraw();
	}
	public void onVisibilityChanged(View v, boolean visibility){
		listener.resize(this.getWidth(), this.getHeight());
		reDraw();
	}

	public void reDraw(){
		this.invalidate();
		/*Canvas canvas = getHolder().lockCanvas();
		if(canvas != null){
			onDraw(canvas);
			getHolder().unlockCanvasAndPost(canvas);
		}*/
	}

}
